﻿using MathTutorPro.DAL;
using MathTutorPro.Data.Entities;
using Microsoft.EntityFrameworkCore;

namespace MathTutorPro.Data.DAL
{
    public class ClassDetailDal
    {
        private readonly AppDbContext _context;

        public ClassDetailDal(AppDbContext context)
        {
            _context = context;
        }

        public async Task<IEnumerable<ClassDetail>> GetByClassIdAsync(int classId, string keyword = null)
        {
            var query = _context.ClassDetail
                .Where(cd => cd.ClassId == classId)
                .Include(cd => cd.User)
                .AsQueryable();

            if (!string.IsNullOrWhiteSpace(keyword))
            {
                query = query.Where(cd =>
                    cd.User.StudentNo.Contains(keyword) ||
                    cd.User.UserName.Contains(keyword));
            }

            return await query.ToListAsync();
        }

        public async Task AddStudentToClassAsync(int classId, string userId)
        {
            _context.ClassDetail.Add(new ClassDetail
            {
                ClassId = classId,
                UserId = userId
            });
            await _context.SaveChangesAsync();
        }

        public async Task<bool> IsStudentInClassAsync(int classId, string userId)
        {
            return await _context.ClassDetail
                .AnyAsync(cd => cd.ClassId == classId && cd.UserId == userId);
        }
    }
}
